package cn.bone.auth.security.base.advice;

import cn.bone.auth.security.base.exception.MyTestException;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.AccessDeniedException;

//@Component
public class HandlerControllerException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Exception ex) {

        ModelAndView mv = new ModelAndView();

        //将异常信息放到request域中,基本上不会使用
        mv.addObject("errorMessage", ex.getMessage());

        if(ex instanceof AccessDeniedException){

            // 403返回页面
            mv.setViewName("redirect:/403");
        }
        else if(ex instanceof MyTestException){
            //自定义错误,返回json数据

            //使用Jackson的视图解析器
//            mv.setView(new MappingJackson2JsonView());
            //使用fastjson的视图解析器
            mv.setView(new FastJsonJsonView());
            mv.addObject("code","101");
            mv.addObject("name","自定义的错误哇");
        }
        else {
            //其他异常
            // 500返回页面
            mv.setViewName("redirect:/500");
        }

        return mv;
    }
}
